<template>
  <div>
    <p class="class-top" style="margin-bottom:20px">商品添加</p>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="商品名称">
        <el-input v-model="form.name" style="width:60%" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" >
      <el-select v-model="form.category"  placeholder="请选择">
    <el-option
      v-for="item in categories"
      :key="item.cateName"
      :label="item.cateName"
      :value="item.cateName">
    </el-option>
  </el-select>
      </el-form-item>
    <el-form-item label="商品价格">
    <el-input-number v-model="form.price" :min="0"></el-input-number>
      </el-form-item>
       <el-form-item label="商品图片">
<el-upload
  class="avatar-uploader"
  action="http://127.0.0.1:5000/goods/goods_img_upload"
  :show-file-list="false"
  :on-success="handupload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
 <el-form-item label="商品描述">
<el-input type="textarea" :rows="4"  v-model="form.goodsDesc" style="width:60%"></el-input>
</el-form-item>
 <el-form-item>
    <el-button type="primary" @click="addgoods">添加商品</el-button></el-form-item>
    </el-form> 


  </div>
</template>

<script>
import {addGoods,getCategories} from "@/apis/goods"
export default {
  data() {
    return {
        imageUrl:'',   //图片回填
         newimg:'',    //图片路径
        categories: [],//商品分类
      form: {
        name: "",    //名字
        price: "",    //价格
        goodsDesc: "",   //描述  
        category:''   //分类 
      },
    };
  },
  methods: {
    
    //上传图片
    handupload(res,file){
      // console.log(res);
      this.newimg=res.imgUrl
      this.imageUrl = URL.createObjectURL(file.raw);
        //  console.log( this.newimg);
    },
//点击添加商品
addgoods(){
  let {name,category,price,goodsDesc}=this.form
  addGoods({name,category,price,goodsDesc,imgUrl: this.newimg,
  }).then((res)=>{
  if (res.data.code==0) {
    this.$message({
          message: '恭喜您，成功添加商品',
          type: 'success'
        });
  }  
  })
}


  },
  created(){
    //查询所有商品的分类
getCategories().then(res=>{
  // console.log(res.data.categories);
  this.categories=res.data.categories
  // console.log( this.form.category);
})
  }
};
</script>

<style lang="less">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>